import { Database, getTableName } from "./database.js";
import { DatabaseSync } from "node:sqlite";
/**
 * Sqlite 数据库操作子类型
 * @class Sqlite
 * @extends Database
 */
export class Sqlite extends Database {
  static engine = "sqlite";

  constructor(filename) {
    super();
    this.db = new DatabaseSync(filename);
    this.sql = this.db.createTagStore();
  }

  #query(method, sql, ...params) {
    if (Array.isArray(sql)) return this.sql[method](sql, ...params);
    const stmt = this.db.prepare(sql);
    if (params.length == 1 && Array.isArray(params[0])) [params] = params;
    return stmt[method](...params);
  }

  async findMany(sql, ...params) {
    return this.#query("all", sql, ...params);
  }

  async findOne(sql, ...params) {
    return this.#query("get", sql, ...params);
  }

  run(sql, ...params) {
    return this.#query("run", sql, ...params);
  }

  async insert(sql, ...params) {
    const { lastInsertRowid } = this.run(sql, ...params);

    if (Array.isArray(sql)) [sql] = sql;
    return this.findOne(
      `select * from ${getTableName(sql)} where id = ?`,
      lastInsertRowid
    );
  }

  async update(sql, ...params) {
    const { changes } = this.run(sql, ...params);
    return changes;
  }

  async delete(sql, ...params) {
    const { changes } = this.run(sql, ...params);
    return changes;
  }

  async end() {
    this.db.close();
  }
}
